using UnityEngine;
using System.Collections;

public class cameraControlScript : MonoBehaviour {

    Transform player = null;
    public float distance = 50f;
    private float targetDistance;
    public int latency = 50;

	// Use this for initialization
	void Start () {
        player = GameObject.Find("ship").transform;
        targetDistance = distance;
	}
	
	// Update is called once per frame
	void FixedUpdate () {
        Vector3 position = new Vector3(player.position.x, transform.position.y, player.position.z);
        transform.position = position;
	}

    void Update()
    {
        calculateTargetDistance();
        reachDistance();
    }

    void calculateTargetDistance()
    {
        shipControllerScript playerScript = player.GetComponent<shipControllerScript>();
        GameObject nextAttract = playerScript.nextTarget;
        float offset = 0;
        if (nextAttract == null)
            nextAttract = playerScript.currentTarget;
        if (playerScript.nextTarget != null)
        {
            Vector3 nextAttractPosition = playerScript.nextTarget.transform.position;
            offset = (nextAttractPosition - player.position).magnitude + distance;
        }
        targetDistance = Mathf.Sqrt(playerScript.speed) * 8 + distance;

        if (targetDistance < offset)
            targetDistance = offset;
    }

    void reachDistance()
    {
        float currentDistance = camera.orthographicSize;
        camera.orthographicSize += (targetDistance - currentDistance) / latency;
    }
}
